/**
  ******************************************************************************
  * @file           : usart.c
  * @brief          : USART middle layer code
  * @author         : Qilong Huang <jcdiyhelp@qq.com>
  * @date           : 2021-06-08 
  * 
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2021 Joy create tech(Suzhou, China) Co., Ltd.
  * All rights reserved.
  *
  *
  ******************************************************************************
  */
/* Global include ---------------------------------------------------------*/
#include "usart.h"
#include "string.h"

/* Global definition-------------------------------------------------------*/
UART_HandleTypeDef huart1;
TYP_UsartBuffer_t UsartBuffer;
/**
  * @brief USART1 Initialization Function
  * @param None
  * @retval None
  */
void USART_uartInit(void)
{
    int i = 0, j = 0;
    huart1.Instance = USART1;
    huart1.Init.BaudRate = 115200;
    huart1.Init.WordLength = UART_WORDLENGTH_8B;
    huart1.Init.StopBits = UART_STOPBITS_1;
    huart1.Init.Parity = UART_PARITY_NONE;
    huart1.Init.Mode = UART_MODE_TX_RX;
    huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
    huart1.Init.OverSampling = UART_OVERSAMPLING_16;
    if (HAL_UART_Init(&huart1) != HAL_OK)
    {
        Error_Handler();
    }
    for (i = 0; i < MAX_USART_BUF; i++)
    {
        for (j = 0; j < MAX_USART_LEN; j++)
        {
            UsartBuffer.BufferBody[i].data[j] = 0x00;
        }
    }
    UsartBuffer.BufferHead = 0x00;
    UsartBuffer.BufferTail = 0x00;
}

/**
  * @brief USART1 send string
  * @param String pointer
  * @retval None
  */
void USART_SendString(SINT8_t *str)
{
    while (*str != '\0')
    {
        HAL_UART_Transmit(&huart1, (uint8_t *)str, 1, 100);
        str++;
    }
}

/**
  * @brief This function handles USART1 global interrupt.
  */
void USART1_IRQHandler(void)
{
    if(USART1->SR & UART_FLAG_RXNE)
    {
        UsartBuffer.BufferBody[UsartBuffer.BufferHead].data[UsartBuffer.BufferBody[UsartBuffer.BufferHead].data_pt++] = (UINT8_t)USART1->DR;
        if(UsartBuffer.BufferBody[UsartBuffer.BufferHead].data_pt >= MAX_USART_LEN)
        {
            UsartBuffer.BufferBody[UsartBuffer.BufferHead].data_pt = 0;
            UsartBuffer.BufferHead ++;
            UsartBuffer.BufferHead &= (MAX_USART_BUF - 1);
        }
        USART1->SR &= ~UART_FLAG_RXNE;
    }
}

/**
  * @brief Clear usart receive queue buffer
  * @param String pointer
  * @retval None
  */
void USART_ClearQueue(void)
{
    int i, j;
    for (i = 0; i < MAX_USART_BUF; i++)
    {
        for (j = 0; j < MAX_USART_LEN; j++)
        {
            UsartBuffer.BufferBody[i].data[j] = 0x00;
        }
    }
    UsartBuffer.BufferHead = 0x00;
    UsartBuffer.BufferTail = 0x00;
}